package com.jf.tzkk.chain.server;

import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jf.tzkk.chain.entity.Chain;
import com.jf.tzkk.chain.entity.LcInfo;
import com.jf.tzkk.chain.mapper.InfoMapper;
import com.jf.tzkk.chain.service.chain.TronCheckTransaction;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 检查交易，处理充值
 *
 * TRX:https://api.trongrid.io
 * ETH:https://api.etherscan.io/api
 * BSC:https://api.bscscan.com/api
 */
@Component
@Slf4j
@AllArgsConstructor
public class CheckTransactionServer implements CommandLineRunner {

    private final TronCheckTransaction tronCheckTransaction;
    private final InfoMapper infoMapper;

    @Override
    public void run(String... args) throws Exception {
        runTransactionThread();
    }

    private void runTransactionThread(){
        log.info("链上充值-扫描线程启动！");
        new Thread(()->{
            int num = 0;
            while (true) {
                try {
                    /**
                     * 暂时只做波场
                     */
                    Chain chain = new Chain();
                    LcInfo info = infoMapper.selectById(1);
                    if(info==null || StringUtils.isBlank(info.getUsdtAddress())){
                        log.error("链上充值-错误：没有有效的收款地址");
                        ThreadUtil.sleep(30000);
                        continue;
                    }
                    chain.setWalletAddress(info.getUsdtAddress());
                    int count = tronCheckTransaction.handleTransactionWithRecharge(chain);
                    log.info("链上充值-本次充值订单数：{}", count);
                    num++;
                }catch (Exception ex) {
                    log.error("链上充值-错误：" + ex.getMessage(), ex);
                } finally {
                    //间隔10秒处理一次
                    ThreadUtil.sleep(10000);
                }
            }
        }).start();
    }
}
